<?php

class Photo extends Controller {
	
	public function __construct() {
		parent::Controller();	

		$this->load->helper(array ('file', 'html'));
	}
	
	
	public function index() {
		$dir_array = array ();
		
		$base_directory = $this->config->item('base_directory');
		
		$dir_handle = opendir($base_directory);
		$dir = readdir($dir_handle);
		
		$file_system_charset = $this->config->item('file_system_charset');
		$charset = $this->config->item('charset');
		
		while ($dir) {
			if ($dir != '.' && $dir != '..') {
				$inner_handle = opendir("{$base_directory}{$dir}");
				
				$cover = readdir($inner_handle);
				while ($cover) {
					if ($cover != '.' && $cover != '..') {
						if (is_image_file($cover)) {
							break;
						}
					}
					
					$cover = readdir($inner_handle);
				}
				
				if ($file_system_charset != $charset) {
					$dir = iconv($file_system_charset, $charset, $dir);
					$cover = iconv($file_system_charset, $charset, $cover);
				}
				
				$dir_array[] = array(
					'path' => $dir,
					'cover' => $this->config->site_url() . '/photo/show/' . $dir . '/' . $cover
				);
			}
			
			$dir = readdir($dir_handle);
		}
		
		$data = array (
			'title' => 'Photo Management System',
			'dir_array' => $dir_array
		);
		
		$suffix = $this->uri->suffix('html');
		$this->load->layout('layouts/photo', "photo/{$suffix}/index", $data);
	}
	
	public function show() {
		$file_system_charset = $this->config->item('file_system_charset');
		$url_charset = $this->config->item('url_charset');
		
		$base_directory = $this->config->item('base_directory');
		
		$file_name = $this->uri->uri_string();
		$file_name = substr($file_name, 11);
	
		$file_extention = $this->uri->suffix();
		
		$file_path = "{$base_directory}{$file_name}.{$file_extention}";
		
		if ($file_system_charset != $url_charset) {
			$file_path = iconv($url_charset, $file_system_charset, $file_path);
		}
		
		if (file_exists($file_path)) {
			$mime_content_type = get_mime_by_extension($file_path);
			header("Content-type: {$mime_content_type}");
		
			readfile($file_path);
		} else {
			echo '132';
		}
	}
	
	public function test() {
		echo urlencode('测试');
	}
}

?>